import pygame
import random

SCREEN_SIZE = (480, 700)


class Bcakground(pygame.sprite.Sprite):
    def __init__(self, is_next=False, speed=1):
        super().__init__()
        # 加载图像
        self.image = pygame.image.load('./images/background.png')
        # 获取矩形区域
        self.rect = self.image.get_rect()
        self.speed = speed
        # 是否是下一个
        if is_next:
            # 设置左上角y坐标
            self.rect.y = -SCREEN_SIZE[1]

    def update(self):
        """更新"""
        self.rect.y += self.speed
        if self.rect.y >= SCREEN_SIZE[1]:
            self.rect.y = -SCREEN_SIZE[1]


class PlaneSprite(pygame.sprite.Sprite):
    """我方飞机类"""

    def __init__(self):
        super().__init__()
        self.image = pygame.image.load('./images/me1.png')
        self.rect = self.image.get_rect()
        # self.rect.inflate(200, 200)
        self.speed = 1
        # 设置中心点x的坐标
        self.rect.centerx = 240
        # 设置中心点y的坐标
        self.rect.centery = 600
        # 创建子弹的精灵组
        self.bullet_group = pygame.sprite.Group()

    def fire(self):
        """开火发射子弹"""
        y = self.rect.y
        for i in range(3):
            bullet = Bullet(self.rect.centerx, y)
            self.bullet_group.add(bullet)
            y += 20


class EnemySprite(pygame.sprite.Sprite):
    """敌方飞机"""

    def __init__(self):
        super().__init__()
        self.image = pygame.image.load('./images/enemy1.png')
        self.rect = self.image.get_rect()
        self.speed = 1
        self.rect.x = random.randint(30, 400)
        self.rect.y = 0

    def update(self, *args):
        self.rect.y += self.speed


class Bullet(pygame.sprite.Sprite):
    """子弹类"""

    def __init__(self, x, y, speed=1):
        super().__init__()
        self.image = pygame.image.load('./images/bullet1.png')
        self.rect = self.image.get_rect()
        self.speed = speed
        self.rect.x = x
        self.rect.y = y

    def update(self, *args):
        self.rect.y -= self.speed
        if self.rect.y < 0:
            self.kill()


class PlaneGame():
    def __init__(self):

        #  初始化
        pygame.init()
        # 设置屏幕窗口大小
        self.screen = pygame.display.set_mode(SCREEN_SIZE)
        # 设置标题名称
        pygame.display.set_caption('飞机大战')
        # 是否循环
        self.is_loop = True
        # 是否结束
        self.is_end = False
        # 设置时钟
        self.clock = pygame.time.Clock()
        pygame.time.set_timer(pygame.USEREVENT, 2000)
        # 定时去发射子弹
        pygame.time.set_timer(30, 1500)
        self.__create_sprites()

    def start(self):
        while self.is_loop:
            self.screen.fill((0, 0, 0))
            self.__event_handler()
            self.__update_sprites()
            if self.is_end:
                image = pygame.image.load('./images/gameover.png')
                rect = image.get_rect()
                self.screen.blit(image, rect)
            # 限制每秒不能超过40帧
            self.clock.tick(40)
            # 更新
            pygame.display.update()
        pygame.quit()

    def __event_handler(self):
        """事件处理"""
        # 获取所有事件
        for e in pygame.event.get():
            if e.type == pygame.QUIT:
                self.is_loop = False
            elif e.type == pygame.KEYDOWN:
                if e.key == pygame.K_LEFT:
                    self.plane.rect.x -= 10
                    if self.plane.rect.x < 0:
                        self.plane.rect.x = 10
                elif e.key == pygame.K_RIGHT:
                    self.plane.rect.x += 10
                    if self.plane.rect.x > SCREEN_SIZE[0] - self.plane.rect.w:
                        self.plane.rect.x = SCREEN_SIZE[0] - self.plane.rect.w - 10
            elif e.type == pygame.USEREVENT:
                enemy = EnemySprite()
                self.enemy_group.add(enemy)
            #     处理30的事件，发射子弹
            elif e.type == 30:
                self.plane.fire()

    def __create_sprites(self):
        """创建精灵"""
        # 创建对象
        bg = Bcakground()
        bg1 = Bcakground(True)
        # 将bg bg1 精灵添加精灵组当中
        self.bg_group = pygame.sprite.Group(bg, bg1)
        #     创建对象
        self.plane = PlaneSprite()
        self.plane_group = pygame.sprite.Group(self.plane)
        # 创建敌方飞机
        enemy = EnemySprite()
        self.enemy_group = pygame.sprite.Group(enemy)

    def __update_sprites(self):
        """更新精灵"""
        # 判断敌方飞机和子弹是否命中
        pygame.sprite.groupcollide(self.plane.bullet_group, self.enemy_group, True, True)
        sprites = pygame.sprite.spritecollide(self.plane, self.enemy_group, True)
        if len(sprites) > 0:
            self.clear()
            self.is_end = True
        # 调用包含的精灵的更新方法
        self.bg_group.update()
        # 将精灵图像放到屏幕上
        self.bg_group.draw(self.screen)
        self.plane_group.draw(self.screen)
        # 敌方飞机的更新跟渲染
        self.enemy_group.update()
        self.enemy_group.draw(self.screen)
        # 子弹的更新和渲染
        self.plane.bullet_group.update()
        self.plane.bullet_group.draw(self.screen)

    def clear(self):
        """清除内容"""
        self.enemy_group.empty()
        self.plane.bullet_group.empty()
        self.plane_group.empty()
        pygame.time.set_timer(pygame.USEREVENT, 0)
        # 定时去发射子弹
        pygame.time.set_timer(30, 0)


plane = PlaneGame()
plane.start()
